display("shoptype,shoparea"); // 需要翻译的类型
var shopSubclass = null;
var shopCity = null;
$(function() {
	//商户的编辑弹出框
	$('#businessEditDialog').dialog({
		buttons : [ {
			text : '保存',
			handler : function() {
				if (!$('#businessEditForm').form('validate')) {
					return;
				}
				var shopCover = $("#shopCover").val();
				if(shopCover=='' || shopCover==null){
					$.messager.alert('操作提示', '请上传商家封面！', 'error');
					return false;
				}
				//验证用户名
				var isVal = 1;
				var username = $("#username").val();
				var userId = $("#userId").val();
				$.ajax({
	 	            type:'post',
	 	            url:'business/checkUnById.html',
	 	            data:'username='+username+'&id='+userId,
	 	            dataType:'json',
	 	            async: false,
	 	            success:function(r){
	 	            	if (r.r) {
							if(r.count>0){
								isVal=0;
								$.messager.alert('操作提示', '该登陆名已存在！', 'error');
								return false;
							}else{
								isVal=1;
							}
						} else {
							$.messager.alert('操作提示', r.m, 'error');
						}
	 	            }
	            });
				if(isVal==0){
                	return false;
                }
				
				//验证商户名称
				var isShopName = 1;
				var shopName = $("#shopName").val();
				var id = $("#id").val();
;				$.ajax({
	 	            type:'post',
	 	            url:'business/checkShopName.html',
	 	            data:'shopName='+shopName+'&id='+id,
	 	            dataType:'json',
	 	            async: false,
	 	            success:function(r){
	 	            	if (r.r) {
							if(r.count>0){
								isShopName=0;
								$.messager.alert('操作提示', '该商户名称已存在！', 'error');
								return false;
							}else{
								isShopName=1;
							}
						} else {
							$.messager.alert('操作提示', r.m, 'error');
						}
	 	            }
	            });
				if(isShopName==0){
                	return false;
                }
				$('#businessEditForm')._ajaxForm(function(r) {
					if (r.r) {
						$('#businessEditDialog').dialog('close');
						$('#grid').datagrid('reload');
					} else {
						$.messager.alert('操作提示', r.m, 'error');
					}
				});
			}
		}, {
			text : '关闭',
			handler : function() {
				$('#businessEditDialog').dialog('close');
			}
		} ]
	});
	var grid = $('#grid')._datagrid({
		checkOnSelect : false,
		selectOnCheck : false,
		toolbar : [{
            text : '创建商户',
            iconCls : 'icon-add',
            handler : handler_add
        }]
	});
	/*新增商户*/
    function handler_add() {
        $('#businessEditForm').attr('action','business/add.html').resetForm();
        $('#id').val('');
        $('#username').removeAttr('readonly');
        $('#shopCover').val('');
        $("#imagePhoto").attr("src",'');
        $("#imagePhoto").empty();
        $('#businessEditDialog').dialog('open').dialog("setTitle","新增商户");
    }
	$('#queryButton').click(function() {
		var params = $('#queryForm')._formToJson();
		$(grid).datagrid('load', params);
	});
});
var formatter = {
	status : function(value, rowData, rowIndex) {
		if (value == 1) {
			return '<font color=green>可登陆</font>';
		} else {
			return '<font color=red>不可登陆</font>';
		}
	},
	payEnable : function(value, rowData, rowIndex) {
		if (value == 1) {
			return '<font color=green>启用</font>';
		} else {
			return '<font color=red>禁用</font>';
		}
	},
	shopType : function(value, rowData, rowIndex) {
		if($.fn.display.shoptype[value]==undefined &&$.fn.display.shoptype[rowData.shopSubclass]==undefined){
			return "";
		}else if($.fn.display.shoptype[value]!=undefined && $.fn.display.shoptype[rowData.shopSubclass]==undefined){
			return $.fn.display.shoptype[value]+"，";
		}else if($.fn.display.shoptype[value]!=undefined && $.fn.display.shoptype[rowData.shopSubclass]!=undefined){
			return $.fn.display.shoptype[value]+"，"+$.fn.display.shoptype[rowData.shopSubclass];
		}
    },
    shopArea : function(value, rowData, rowIndex) {
    	if($.fn.display.shoparea[value]==undefined &&$.fn.display.shoparea[rowData.shopCity]==undefined){
			return "";
		}else if($.fn.display.shoparea[value]!=undefined && $.fn.display.shoparea[rowData.shopCity]==undefined){
			return $.fn.display.shoparea[value]+"，";
		}else if($.fn.display.shoparea[value]!=undefined && $.fn.display.shoparea[rowData.shopCity]!=undefined){
			return $.fn.display.shoparea[value]+"，"+$.fn.display.shoparea[rowData.shopCity];
		}
    },
	opt : function(value, rowData, rowIndex) {
		var html = '<a class="spacing a-blue" onclick="updShop(' + rowIndex+ ');" href="javascript:void(0);">修改</a>';
		html += '<a class="spacing a-green" onclick="resetPassword(' + rowIndex+ ');" href="javascript:void(0);">重置密码</a>';
		return html;
	}
};
/* 修改商户 */
function updShop(rowIndex) {
	var data = $('#grid').datagrid('getRows')[rowIndex];
	$('#businessEditForm').attr('action', 'business/upd.html').resetForm();
	$("#imagePhoto").attr("src", 'document/file-'+data.shopCover+'.do' );
	$('#username').attr('readonly', 'readonly');
	$("#phoAdd").val('替换封面');
	$('#businessEditForm')._jsonToForm(data);
	shopSubclass=data.shopSubclass;
	shopCity=data.shopCity;
	$('#businessEditDialog').dialog('open').dialog('setTitle', '修改商户');
}

//商户重置密码
function resetPassword(rowIndex) {
	$.messager.confirm('操作提示', '是否重置密码为‘111111’？', function(r) {
		if (r) {
			var data = $('#grid').datagrid('getRows')[rowIndex];
			$._ajaxPost('business/resetPassword.html', {
				id : data.id,
				userId : data.userId
			}, function(r) {
				if (r.r) {
					$('#grid').datagrid('reload');
				} else {
					$.messager.alert('操作提示', r.m, 'error');
				}
			});
		}
	});
}


//根据商户类型选择商户子类型
function selectChildShopType(){
	var shopType=$("#shopType").val();
	if (shopType == "" || shopType == null) {
		$("#shopSubclass").empty();
		$("#shopSubclass").append("<option value=''>==请选择==</option>");
		$('#shopSubclass')._pullDownList('refresh');
		return;
	}
	$._ajaxPost('business_type_sub.html', {parentId:shopType}, function(r) {
		if (r.r) {
			$("#shopSubclass").empty();
			$("#shopSubclass").append("<option value=''>==请选择==</option>");
			var list = r.parentTypes;
			for ( var i = 0; i < list.length; i++) {
				$("#shopSubclass").append("<option value='" + list[i].id + "'>" + list[i].name + "</option>");
			}
			$('#shopSubclass').val(shopSubclass);
			$('#shopSubclass')._pullDownList('refresh');
		} else {
			$.messager.alert('操作提示', r.m, 'error');
		}
	});
}

//根据商户类型选择商户子类型（条件查询）
function selectChildShopType1(){
	var shopType=$("#shopType1").val();
	if (shopType == "" || shopType == null) {
		$("#shopSubclass1").empty();
		$("#shopSubclass1").append("<option value=''>==请选择==</option>");
		$('#shopSubclass1')._pullDownList('refresh');
		return;
	}
	$._ajaxPost('business_type_sub.html', {parentId:shopType}, function(r) {
		if (r.r) {
			$("#shopSubclass1").empty();
			$("#shopSubclass1").append("<option value=''>==请选择==</option>");
			var list = r.parentTypes;
			for ( var i = 0; i < list.length; i++) {
				$("#shopSubclass1").append("<option value='" + list[i].id + "'>" + list[i].name + "</option>");
			}
			$('#shopSubclass1')._pullDownList('refresh');
		} else {
			$.messager.alert('操作提示', r.m, 'error');
		}
	});
}

//根据商户区域选择商户子城市
function selectChildShopArea(){
	var shopArea=$("#shopArea").val();
	if (shopArea == "" || shopArea == null) {
		$("#shopCity").empty();
		$("#shopCity").append("<option value=''>==请选择==</option>");
		$('#shopCity')._pullDownList('refresh');
		return;
	}
	$._ajaxPost('shop_city.html', {parentId:shopArea}, function(r) {
		if (r.r) {
			$("#shopCity").empty();
			$("#shopCity").append("<option value=''>==请选择==</option>");
			var list = r.area;
			for ( var i = 0; i < list.length; i++) {
				$("#shopCity").append("<option value='" + list[i].id + "'>" + list[i].name + "</option>");
			}
			$('#shopCity').val(shopCity);
			$('#shopCity')._pullDownList('refresh');
		} else {
			$.messager.alert('操作提示', r.m, 'error');
		}
	});
}

//google定位获取经纬度信息
function google(){
	var address=$("#shopAddress").val();
	if(address!=""&&address!=null){
		var url = "http://ditu.google.cn/maps/api/geocode/json?address=" + encodeURIComponent(address) + "&sensor=false" + "&randomNum=" + Math.random();
        $.ajax({
            url: url,
            dataType: 'json',
            success: function(data) {
                if (data.status == 'OK') {
               	//经度
               	 var lng=data.results[0].geometry.location.lng;
               	 $("#shopLog").val(lng);
               	//纬度
               	 var lat=data.results[0].geometry.location.lat;
               	 $("#shopLat").val(lat);
                }else {
                	 $("#shopLat").val("");
                	 $("#shopLog").val("");
                	 $.messager.alert('操作提示', "没找到你要查询的位置，请重新输入！", 'error');
                }
            },
            error: function() {
           	 $("#shopLat").val("");
            	 $("#shopLog").val("");
            	 $.messager.alert('操作提示', "网络繁忙，请重试！", 'error');
            }
        });
	 }else{
		 $.messager.alert('操作提示', "请输入需要定位的商家地址,谢谢！", 'error');
	 }
}
$(function(){
	//添加图片
    $("#phoAdd").click(function(){
      $("#fileImage").click();
    });
    var params = {
   	    fileInput: $("#fileImage").get(0),
   	    upButton: "",
   	    url: 'document/upload-img.do',//上传地址
   	    filter: function(files) {
   	        var arrFiles = [];
   	        for (var i = 0, file; file = files[i]; i++) {
   	            if (file.type.indexOf("image") == 0) {
   	                 if (file.size >= 5120000) {
   	                	$.messager.alert('操作提示', 'Picture "'+ file.name +'" too big.', 'error');
   	                 } else {
   	                    arrFiles.push(file);    
   	                 }           
   	            } else {
   	            	$.messager.alert('操作提示', 'File "' + file.name + '" is not a picture.', 'error');
   	            }
   	        }
   	        return arrFiles;
   	    },
   	    onSelect: function(files) {
   	        var i = 0;
   	        var funAppendImage = function() {
   	            file = files[i];
   	            if (file) {
   	                var reader = new FileReader()
   	                reader.onload = function(e) {
   	                	$("#imagePhoto").attr("src", e.target.result );
   	                	i++;
   	                    funAppendImage();
   	                }
   	                reader.readAsDataURL(file);
   	            } else {
   	            	ZXXFILE.funUploadFile();
   	                ZXXFILE.fileFilter=[];
   	            }
   	        };
   	        funAppendImage();       
   	    },
   	    onProgress: function(file, loaded, total) {
   	    	
   	    },
   	    onSuccess: function(file, response) {
   	        var obj = eval("("+response+")");  
   	        var dataId = obj['d']['fileToUpload']['fileId'];
   	        $("#shopCover").val(dataId);
   	     	$("#imagePhoto").attr("src", 'document/file-'+dataId+'.do' );
   	    },
   	    onFailure: function(file) {
   	    	
   	    },
   	    onComplete: function() {
   	       //file控件value置空
   	      $("#fileImage").val("");
   	    }
   	};
   	ZXXFILE = $.extend(ZXXFILE, params);
   	ZXXFILE.init();
});
/**导出*/
$(function() {
	$('#excelExport').click(function(){
		var shopName = $("#shopName").val();
		var id = $("#id").val();
		var channelName = $("#channelName").val();
	   	var shopType = $("#shopType1").val();
	   	var state = $("#state").val();
	   	var shopSubclass =$("#shopSubclass1").val();
	   	var payEnable =$("#payEnable").val(); 
	   document.location.href = "/businessExport.html?shopName=" + shopName+"&id="+id+"&channelName="+channelName+"&shopType="+shopType+"&state="+state+"&shopSubclass="+shopSubclass+"&payEnable="+payEnable;
	});
});